package com.chkj.fbook.system.controller;

import com.chkj.fbook.common.utils.MD5Utils;
import com.chkj.fbook.common.utils.PageUtils;
import com.chkj.fbook.common.utils.Query;
import com.chkj.fbook.common.utils.R;
import com.chkj.fbook.system.service.RoleService;
import com.chkj.fbook.system.service.UserService;
import com.chkj.fbook.common.annotation.Log;
import com.chkj.fbook.common.annotation.Permission;
import com.chkj.fbook.common.controller.BaseController;
import com.chkj.fbook.common.domain.Tree;
import com.chkj.fbook.system.domain.DeptDO;
import com.chkj.fbook.system.domain.RoleDO;
import com.chkj.fbook.system.domain.UserDO;
import com.chkj.fbook.system.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RequestMapping("/sys/user")
@Controller
public class UserController extends BaseController {

    private String prefix = "system/user";

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @Log("后台用户-去到列表页面")
    @GetMapping("")
    public String user(Model model) {
        return prefix + "/user";
    }

    @Log("后台用户-获取列表信息")
    @GetMapping("/list")
    @ResponseBody
    public PageUtils list(@RequestParam Map<String, Object> params) {
        // 查询列表数据
        Query query = new Query(params);

        if (!"admin".equals(this.getUsername())) {
            query.put("admin", "admin");
        }

        List<UserDO> sysUserList = userService.list(query);
        int total = userService.count(query);
        PageUtils pageUtil = new PageUtils(sysUserList, total);
        return pageUtil;
    }

    @Log("后台用户-去到添加页面")
    @Permission(name = "sys:user:add")
    @GetMapping("/add")
    public String add(Model model) {
        RoleDO roleDO = new RoleDO();
        if (!"admin".equals(this.getUsername())) {
            roleDO.setRoleSign("admin");
        }
        List<RoleDO> roles = roleService.listAll(roleDO);
        model.addAttribute("roles", roles);
        return prefix + "/add";
    }

    @Log("后台用户-去到修改页面")
    @Permission(name = "sys:user:edit")
    @GetMapping("/edit/{id}")
    public String edit(Model model, @PathVariable("id") String id) {
        UserDO userDO = userService.get(id);
        model.addAttribute("user", userDO);
        RoleDO roleDO = new RoleDO();
        roleDO.setUserId(id);
        if (!"admin".equals(this.getUsername())) {
            roleDO.setRoleSign("admin");
        }
        List<RoleDO> roles = roleService.listAll(roleDO);
        model.addAttribute("roles", roles);
        return prefix + "/edit";
    }

    @Log("后台用户-保存操作")
    @Permission(name = "sys:user:add")
    @PostMapping("/save")
    @ResponseBody
    public R save(UserDO user) {
        user.setPassword(MD5Utils.encryptPassword(MD5Utils.md5(user.getPassword())));
        if (userService.save(user) > 0) {
            return R.ok();
        }
        return R.error();
    }

    @Log("后台用户-更新操作")
    @Permission(name = "sys:user:edit")
    @PostMapping("/update")
    @ResponseBody
    public R update(UserDO user) {
        if (userService.update(user) > 0) {
            return R.ok();
        }
        return R.error();
    }


    @Log("后台用户-修改个人信息操作")
    @Permission(name = "sys:user:edit")
    @PostMapping("/updatePeronal")
    @ResponseBody
    public R updatePeronal(UserDO user) {
        if (userService.updatePersonal(user) > 0) {
            return R.ok();
        }
        return R.error();
    }

    @Log("后台用户-删除操作")
    @Permission(name = "sys:user:remove")
    @PostMapping("/remove")
    @ResponseBody
    public R remove(String id) {
        if (userService.remove(id) > 0) {
            return R.ok();
        }
        return R.error();
    }

    @Log("后台用户-批量删除")
    @Permission(name = "sys:user:batchRemove")
    @PostMapping("/batchRemove")
    @ResponseBody
    public R batchRemove(@RequestParam("ids[]") String[] userIds) {
        int r = userService.batchremove(userIds);
        if (r > 0) {
            return R.ok();
        }
        return R.error();
    }

    @PostMapping("/exit")
    @ResponseBody
    public boolean exit(@RequestParam Map<String, Object> params) {
        // 存在，不通过，false
        return !userService.exit(params);
    }

    @Log("后台用户-去到请求更改用户密码页面")
    @Permission(name = "sys:user:resetPwd")
    @GetMapping("/resetPwd/{id}")
    public String resetPwd(@PathVariable("id") String userId, Model model) {

        UserDO userDO = new UserDO();
        userDO.setUserId(userId);
        model.addAttribute("user", userDO);
        return prefix + "/reset_pwd";
    }

    @Log("后台用户-提交更改用户密码操作")
    @PostMapping("/resetPwd")
    @ResponseBody
    public R resetPwd(UserVO userVO) {
        try {
            userService.resetPwd(userVO, getUserDO());
            return R.ok();
        } catch (Exception e) {
            return R.error(1, e.getMessage());
        }

    }

    @Log("后台用户-admin提交更改用户密码")
    @Permission(name = "sys:user:resetPwd")
    @PostMapping("/adminResetPwd")
    @ResponseBody
    public R adminResetPwd(UserVO userVO) {
        try {
            userService.adminResetPwd(userVO);
            return R.ok();
        } catch (Exception e) {
            return R.error(1, e.getMessage());
        }

    }

    @GetMapping("/tree")
    @ResponseBody
    public Tree<DeptDO> tree() {
        Tree<DeptDO> tree = userService.getTree();
        return tree;
    }

    @GetMapping("/treeView")
    public String treeView() {
        return prefix + "/userTree";
    }

    @Log("后台用户-查看个人信息")
    @GetMapping("/personal")
    public String personal(Model model) {
        UserDO userDO = userService.get(getUserId());
        model.addAttribute("user", userDO);
        return prefix + "/personal";
    }

    @ResponseBody
    @PostMapping("/uploadImg")
    public R uploadImg(@RequestParam("avatar_file") MultipartFile file, String avatar_data, HttpServletRequest request) {
        Map<String, Object> result;
        try {
            result = userService.updatePersonalImg(file, avatar_data, getUserId());
        } catch (Exception e) {
            return R.error("更新图像失败！");
        }
        if (result != null && result.size() > 0) {
            return R.ok(result);
        } else {
            return R.error("更新图像失败！");
        }
    }

    @GetMapping("/user2")
    public String user2(HttpServletRequest requst, Model model) {
        String urlstr = requst.getParameter("urlstr");
        model.addAttribute("urlstr", urlstr);
        return prefix + "/user2";
    }
}
